package com.qf.xiaomi.dao.impl;

import com.qf.xiaomi.dao.GoodsDao;
import com.qf.xiaomi.pojo.Goods;
import com.qf.xiaomi.utils.DataSourceUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * @author 千锋教育
 * @Company http://www.mobiletrain.org/
 * @Version 1.0
 */
public class GoodsDaoImpl implements GoodsDao {
    @Override
    public long getTotalCount(int typeId) {
        QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());
        String sql = "select count(1) from tb_goods where typeId = ?";

        try {
            long count = (long) qr.query(sql, new ScalarHandler(), typeId);
            return count;
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("查询商品总条数失败");
        }
        return 0;
    }

    @Override
    public List<Goods> getData(int typeId, int startIndex, int pageSize) {
        QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());
        String sql = "select * from tb_goods where typeId = ? limit ?, ?";

        try {
            List<Goods> goodsList = qr.query(sql, new BeanListHandler<>(Goods.class), typeId, startIndex, pageSize);
            return goodsList;
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("查询商品分页数据失败");
        }
        return null;
    }

    @Override
    public Goods findById(int id) {
        QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());
        String sql = "select * from tb_goods where id = ?";
        try {
            Goods goods = qr.query(sql, new BeanHandler<>(Goods.class), id);
            return goods;
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("获取商品详情失败");
        }
        return null;
    }
}
